package io.github.hayeka.a2_howtodebugsimulateconcurrentscene.controller;

import io.github.hayeka.a2_howtodebugsimulateconcurrentscene.dao.UserDao;
import io.github.hayeka.a2_howtodebugsimulateconcurrentscene.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program:
 * @description:
 * @author:
 * @create: 2021/9/3
 **/

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired
    private UserDao userDao;

    @GetMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {

        log.info("[{}]在处理这个请求", Thread.currentThread().getName());

        HashMap<String, Object> map = new HashMap<>();

        boolean existFlag = checkEmailExist(user);

        if (!existFlag) {
            userDao.save(user);
            map.put("code", "200");
            map.put("msg", "注册成功");
            return map;
        } else {
            map.put("code", "200");
            map.put("msg", "注册失败,Email已经存在");
            return map;
        }
    }

    private boolean checkEmailExist(User user) {

        List<User> users = userDao.findByEmail(user.getEmail());
        if (null != users && users.size() > 0) {
            log.info("查到了此邮件:[{}]", user.getEmail());
            return true;
        } else {
            log.info("没有查到此邮件:[{}]", user.getEmail());
            return false;
        }

    }

}
